package cn.mccraft.uide.core.workspace;

import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import java.util.Optional;
import cn.mccraft.uide.api.project.Project;
import cn.mccraft.uide.api.workspace.ProjectAlreadyExistsException;

public class Workspace implements cn.mccraft.uide.api.workspace.Workspace {
	
	private final Path path;
	private final Map<String,Project> projects;
	
	private final List<Project> selectedProjects;
	
	public Workspace(Path path) {
		this.path = requireNonNull(path);
		this.projects = new HashMap<>();
		this.selectedProjects = new LinkedList<>();
	}

	@Override
	public Path getPath() {
		return path;
	}

	@Override
	public Optional<Project> getProject(String name) {
		return Optional.ofNullable(projects.get(name));
	}

	@Override
	public void addProject(Project project) {
		if(projects.containsKey(project.getName()))
			throw new ProjectAlreadyExistsException(String.format("Project \"%s\" already exists.", project.getName()));
		projects.put(project.getName(), project);
	}

	@Override
	public boolean removeProject(String name) {
		Optional<Project> project = getProject(name);
		if(project.isPresent()) {
			project.get().close();
			projects.remove(name);
		}
		return true;
	}

	@Override
	public boolean removeProject(Project project) {
		return removeProject(project.getName());
	}

	@Override
	public boolean hasProject(String name) {
		return projects.containsKey(name);
	}

	@Override
	public Optional<Project> getSelectedProject() {
		return selectedProjects.isEmpty() ? Optional.empty() : Optional.of(selectedProjects.get(0));
	}

	@Override
	public Collection<Project> getSelectedProjects() {
		return selectedProjects;
	}

	@Override
	public Collection<Project> getProjects() {
		return projects.values();
	}

	@Override
	public void update() {
		for (Project project : getProjects()) {
			project.update();
		}
	}

	@Override
	public void save() {
		for (Project project : getProjects()) {
			project.save();
		}
	}

}
